#! /usr/bin/env python

import pango

import gtk

import os
import os.path
from os.path import basename

from sugar.datastore import datastore
import sugar.mime

from ftplib import FTP

import commands

datastorepath="/home/olpc/.sugar/default/datastore/store/"
schoolserveraddress=""
serveruser=""
serverpass=""
printingdir="forprinting"
gradingdir="forgrading"

class FileUploader:
	def __init__(self):
		table=gtk.Table(11,2,True)
		
		scrolledwindow=gtk.ScrolledWindow()
		scrolledwindow.set_policy(gtk.POLICY_AUTOMATIC,gtk.POLICY_ALWAYS)
		
		table.attach(scrolledwindow,0,2,0,8,xpadding=2,ypadding=2)
		
		liststore=gtk.ListStore(int,str,str,str,str)
		self.treeview=gtk.TreeView(liststore)
		
		scrolledwindow.add_with_viewport(self.treeview)
		
		textrenderer=gtk.CellRendererText()
		
		column1=gtk.TreeViewColumn('File Name',textrenderer,text=1)
		column1.set_sort_column_id(1)
		self.treeview.append_column(column1)
		
		column2=gtk.TreeViewColumn('Date',textrenderer,text=2)
		column2.set_sort_column_id(2)
		self.treeview.append_column(column2)
		
		column3=gtk.TreeViewColumn('Time',textrenderer,text=3)
		column3.set_sort_column_id(3)
		self.treeview.append_column(column3)
		
		column4=gtk.TreeViewColumn('Hash',textrenderer,text=4)
		column4.set_sort_column_id(4)
		self.treeview.append_column(column4)
		
		query = {}

		query['query'] = ""

		objects, count = datastore.find(query, sorting='-mtime')

		for i in range(count):
			if not objects[i].file_path:
				objects[i].destroy()
				continue
			else:
				title = objects[i].metadata.get_dictionary()['title'].strip()
				mime_type = objects[i].metadata.get_dictionary()['mime_type']	
				ext = sugar.mime.get_primary_extension(mime_type)
				filename = objects[i].metadata.get_dictionary()['filename']	
				mtime = objects[i].metadata.get_dictionary()['mtime'].split('T')
				
				if filename:
					title = title + " (" + filename + ")"
					
				if not ext:
					ext = "file"
					
				itt=liststore.append([i,title+"." + ext,mtime[0],mtime[1],datastorepath+basename(objects[i].file_path).split(".")[0]])
				objects[i].destroy()

		button1=gtk.Button("Upload for Printing")
		
		button1.connect('clicked',self.on_btn_printing)
		
		button2=gtk.Button("Upload for Grading")
		
		button2.connect('clicked',self.on_btn_grading)
		
		table.attach(button1, 0,1,8,10,xpadding=2,ypadding=2)
		table.attach(button2, 1,2,8,10,xpadding=2,ypadding=2)
		
		self.debug = gtk.Label('')
		self.set_msg("Welcome to <b>File Uploader</b>!")
		
		table.attach(self.debug,0,2,10,11)

		self.widget = table
		
	def get_nick(self):
		return commands.getoutput('sugar-control-panel -g nick')
		
	def set_msg(self,string):
		self.debug.set_markup(string)
	
	def cdmkd(self,ftp,dirname):
		try:
			ftp.cwd(dirname)
		except:
			ftp.mkd(dirname)
			ftp.cwd(dirname)
			
	def upload_file(self,ftp,remotefile,localfile):
		ext = remotefile.split('.')[1]
		
		if ext in ("txt","htm","html"):
			self.set_msg("Uploading text file " + remotefile + ".")
			ftp.storlines("STOR " + remotefile,open(localfile))
		else:
			self.set_msg("Uploading binary file " + remotefile + ".")
			ftp.storbinary("STOR " + remotefile,open(localfile,"rb"),1024)
		
	def on_btn_printing(self, *args):
		self.set_msg("Initializing upload for printing!")
		self.upload_selected_line(printingdir)
		
	def on_btn_grading(self, *args):
		self.set_msg("Initializing upload for grading!")
		self.upload_selected_line(gradingdir)
		
	def upload_selected_line(self,uploaddirectory):
		# Gets the selected line
		model, iter = self.treeview.get_selection().get_selected()
		
		if not iter:
			self.set_msg("No file selected...")
			return
		
		# Gets the nickname of the XO laptop
		nick=self.get_nick()
		
		self.set_msg("Contacting server...")
		
		ftp=FTP(schoolserveraddress)
		
		if ftp.login(serveruser,serverpass):
			self.set_msg("Server connected...")
		else:
			self.set_msg("Server could not be contacted!")
			return
		
		self.cdmkd(ftp,uploaddirectory)
		
		self.cdmkd(ftp,nick)
		
		self.upload_file(ftp,model.get_value(iter,1),model.get_value(iter,4))
		
		ftp.quit()
		
		self.set_msg("File uploaded!")
		
